<?php
class RolesController extends Controller
{
	public $layout = 'main';

	public function actionIndex()
	{
		//get params
		$intPage 		= Yii::app()->request->getParam('page', 1);
		$intRowsPerPage = Yii::app()->request->getParam('rpp', MIN_ROWS_PER_PAGE);
		$intSortType 	= Yii::app()->request->getParam('sort',-1);
		
		//list roles
		$arrRoles = Roles::getInstance()->getList(array(), $intPage, $intRowsPerPage);
		$intTotalRows = isset($arrUsers[0]['total_rows'])?$arrUsers[0]['total_rows']:0;
		
		//pagination
		$objPages=new CPagination($intTotalRows);
		$objPages->setCurrentPage($intPage-1);
		$objPages->setPageSize($intRowsPerPage);
		
		//render view
		$this->render('index', array(
			'arrRoles' => $arrRoles,
			'objPages' => $objPages
		));
	}
	
	public function actionForm()
	{
		$intId = Yii::app()->request->getParam('id', null);
		//update data
		if(Yii::app()->request->isPostRequest)
		{
			//update role
			$arrParams = Yii::app()->request->getParam('role', null);
			if(empty($intId)){
				$intResult = Roles::getInstance()->insert($arrParams);
				$intId = $intResult;
			}
			else{
				$intResult = Roles::getInstance()->update($intId, $arrParams);
				$intResult = 1;
			}
			Yii::app()->admin->setFlash('ok', Yii::t('admincp', 'Updated successfully!'));
			$this->refresh();
		}
		//load form
		$arrItemInfo = array();
		if(!empty($intId)){
			$arrItemInfo = Roles::getInstance()->get($intId);
		}
		
		//render layout
		$this->render('form', array(
			'arrItemInfo' => $arrItemInfo
		));
	}
	
	public function actionDelete(){
		$intId = Yii::app()->request->getParam('id', null);
		if(!empty($intId))
			$result = Users::getInstance()->delete($intId);
		header('Location: '.LINK_ADMINCP_USERS);
	}

	public function actionPermissions(){
		$intRoleId = Yii::app()->request->getParam('id', null);
		$role = Roles::getInstance()->get($intRoleId);
		//load role's permissions
		$arrPermissions = Permissions::getInstance()->getRolePermissions($intRoleId);
		if(Yii::app()->request->isPostRequest)
		{
			$arrCustomPermissions = Yii::app()->request->getParam('permissions', array());
			$arrDefaultPermissions = array();
			foreach($arrPermissions as $R){
				array_push($arrDefaultPermissions, $R['permission_id']);	
			}
			$arrDefaultPermissions = array_fill_keys($arrDefaultPermissions, 0);
			$arrCustomPermissions = array_fill_keys($arrCustomPermissions, 1);
			//merge 2 array of custome and default role's permissions
			$arrCustomPermissions = $arrCustomPermissions+$arrDefaultPermissions;
			
			//update db
			Permissions::getInstance()->updateRolePermissions($intRoleId, $arrCustomPermissions);
			
			Yii::app()->admin->setFlash('ok', Yii::t('admincp', 'Updated successfully!'));
			$this->refresh();
		}
		$this->render('permissions', array(
			'role' => $role,
			'arrPermissions' => $arrPermissions
		));	
	}

}